//package com.plian.system.service.pm.listedcompany.impl;
//
//import com.alibaba.fastjson.JSON;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.plian.Tools.*;
//import com.plian.Tools.pagedata.PageData;
//import com.plian.system.cache.UserCache;
//import com.plian.system.common.status.CheckStatus;
//import com.plian.system.constant.sys.FormStatusConstant;
//import com.plian.system.constant.sys.FormTypeConstant;
//import com.plian.system.constant.yth.YthConstant;
//import com.plian.system.entity.pm.listedcompany.BaseEarningsSummary;
//import com.plian.system.entity.pm.listedcompany.EarningsDetail;
//import com.plian.system.entity.sys.ApprovalMessage;
//import com.plian.system.mapper.pm.listedcompany.BaseEarningsSummaryMapper;
//import com.plian.system.model.CommonCode;
//import com.plian.system.model.ListResult;
//import com.plian.system.mybatis.base.BaseFlowService;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.mybatis.search.SearchEntity;
//import com.plian.system.mybatis.search.SearchParamEntiy;
//import com.plian.system.mybatis.support.Condition;
//import com.plian.system.mybatis.support.Query;
//import com.plian.system.properties.GzwProperties;
//import com.plian.system.service.pm.listedcompany.IBaseEarningsSummaryService;
//import com.plian.system.service.pm.listedcompany.IEarningsDetailService;
//import com.plian.system.service.sys.code.IFormCodeService;
//import com.plian.system.service.sys.message.IApprovalMessageService;
//import com.plian.system.service.sys.orgzation.IOrgService;
//import com.plian.system.service.sys.user.ISysUserService;
//import com.plian.system.service.wf.FormWorkflowService;
//import com.plian.system.vo.pm.listedcompany.BaseEarningsSummaryVO;
//import com.plian.system.vo.yth.YthResult;
//import com.plian.system.wrapper.pm.listedcompany.BaseEarningsSummaryWrapper;
//import lombok.AllArgsConstructor;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.web.bind.annotation.RequestBody;
//
//import java.util.*;
//import java.util.stream.Collectors;
//
//import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.INVESTMENT_EXECUTION;
//import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.KT_TYPE;
//import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
//import static com.plian.system.constant.sys.FormTypeConstant.QM_EARNING_REPORT;
//import static com.plian.system.constant.sys.FormTypeConstant.QM_EARNING_REPORT_GZW;
//
///**
// * @Description: TODO
// * @Author: Take-off
// * @Date: 2023/2/28 6:49 PM
// * @Param
// * @return
// * @Version: 1.0
// **/
//@Service
//@AllArgsConstructor
//public class BaseEarningsSummaryServiceImpl extends BaseServiceImpl<BaseEarningsSummaryMapper, BaseEarningsSummary> implements IBaseEarningsSummaryService, BaseFlowService {
//
//    private final IEarningsDetailService earningsDetailService;
//
//    private final BaseEarningsSummaryWrapper baseEarningsSummaryWrapper;
//
//    private final FormWorkflowService formWorkflowService;
//
//    private final IFormCodeService formCodeService;
//
//    private final GzwProperties gzwProperties;
//
//    private IOrgService orgService;
//
//    private ISysUserService userService;
//
//    private IApprovalMessageService approvalMessageService;
//    @Override
//    public boolean saveOrUpdate(BaseEarningsSummary baseEarningsSummary) {
//        boolean flag = false;
//        if (!Optional.ofNullable(baseEarningsSummary.getStatus()).isPresent()) {
//            baseEarningsSummary.setStatus(FormStatusConstant.UNREVIEWED);
//        }
//        if (baseEarningsSummary.getStatus().equals(FormStatusConstant.REJECT)) {
//            baseEarningsSummary.setStatus(FormStatusConstant.UNREVIEWED);
//        }
//        if (!Optional.ofNullable(baseEarningsSummary.getId()).isPresent()) {
//            baseEarningsSummary.setCode(formCodeService.getCode(Integer.parseInt(baseEarningsSummary.getFormType())));
//        }
//        boolean result = super.saveOrUpdate(baseEarningsSummary);
//        return result;
//    }
//
//    @Override
//    public boolean deleteLogic(List<Long> ids) {
//        for (Long id : ids) {
//            BaseEarningsSummary baseEarningsSummary = getById(id);
//            if (baseEarningsSummary == null) {
//                return false;
//            } else if (baseEarningsSummary.getStatus() != null &&
//                    (baseEarningsSummary.getStatus() != FormStatusConstant.STASH && baseEarningsSummary.getStatus() != FormStatusConstant.UNREVIEWED)) {
//                return false;
//            }
//            formWorkflowService.deleteProcessInstance(String.valueOf(id));
//        }
//        boolean result = super.deleteLogic(ids);
//        if (result){
//            earningsDetailService.deleteByParentId(ids);
//        }
//        return result;
//    }
//
//    @Override
//    @Transactional(rollbackFor=RuntimeException.class)
//    public boolean submit(BaseEarningsSummary baseEarningsSummary) {
//        boolean result = saveOrUpdate(baseEarningsSummary);
//        if (result){
//            List<EarningsDetail> earningsDetails = baseEarningsSummary.getEarningsDetails();
//            if (CollectionUtil.isNotEmpty(earningsDetails)){
//                for (EarningsDetail earningsDetail : earningsDetails){
//                    if (earningsDetail.getId() != null &&
//                            Optional.ofNullable(earningsDetail.getIsDeleted()).isPresent() && earningsDetail.getIsDeleted().intValue() == 1) {
//                        earningsDetailService.removeById(earningsDetail.getId());
//                    }else {
//                        earningsDetail.setBaseId(baseEarningsSummary.getId());
//                        earningsDetailService.saveOrUpdate(earningsDetail);
//                    }
//                }
//            }
//        }
//        return result;
//    }
//
//    @Override
//    public BaseEarningsSummaryVO getDetailObj(BaseEarningsSummary baseEarningsSummary) {
//        BaseEarningsSummary detail = getOne(Condition.getQueryWrapper(baseEarningsSummary));
//        BaseEarningsSummaryVO baseExpenditureItemsVO = baseEarningsSummaryWrapper.entityToVO(detail);
//        if (Optional.ofNullable(baseExpenditureItemsVO).isPresent()) {
//            //子项
//            List<EarningsDetail> details = earningsDetailService.list(new LambdaQueryWrapper<EarningsDetail>().eq(EarningsDetail::getBaseId, baseExpenditureItemsVO.getId()));
//            baseExpenditureItemsVO.setEarningsDetails(details);
//        }
//        return baseExpenditureItemsVO;
//    }
//
//    @Override
//    public ListResult<BaseEarningsSummaryVO> list(@RequestBody Query query) {
//        List<SearchEntity> entityList = query.getSearch();
//        if (query.getAscs()==null&&query.getDescs()==null){
//            query.setDescs("create_time");
//        }
//        QueryWrapper<BaseEarningsSummary> queryWrapper = SearchParamEntiy.getQueryWrapper(
//                Condition.getQueryWrapper(new BaseEarningsSummary()), entityList
//        );
//        //只查看自己填写的单据
//        String orgId = TokenUtil.getTokenOrgId();
//        if ( !gzwProperties.getIsGzw(orgId)){
//            queryWrapper.eq("filling_org_id", orgId);
//        }
//
//        IPage<BaseEarningsSummary> pages = page(Condition.getPage(query), queryWrapper);
//        List<BaseEarningsSummaryVO> baseExpenditureItemsVOS = baseEarningsSummaryWrapper.entityToVO(pages.getRecords());
//        ListResult<BaseEarningsSummaryVO> listResult = new ListResult<>(CommonCode.SUCCESS);
//        listResult.setList(baseExpenditureItemsVOS);
//        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
//        return listResult;
//    }
//
//    @Override
//    public HashMap<String,Object> commit(String id) {
//        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW, "");
//
//        //将需要提交的流程变量返回，用于工作流侧
//        return new HashMap<String,Object>();
//    }
//
//    @Override
//    public Boolean finish(String id) {
//        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH,"审批通过");
//    }
//
//    @Override
//    public Boolean reject(String id, int formState,String comment) {
//        return handleStatus(Long.valueOf(id), formState,comment);
//    }
//
//    @Override
//    public List<PageData> findByIds(List<String> formIds) {
//        LambdaQueryWrapper<BaseEarningsSummary> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.in(BaseEarningsSummary::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
//        List<BaseEarningsSummary> baseEarningsSummaries = list(queryWrapper);
//        List<BaseEarningsSummaryVO> baseEarningsSummaryVOS = baseEarningsSummaryWrapper.entityToVO(baseEarningsSummaries);
//        List<PageData> pageDataList = new ArrayList<>();
//        try{
//            if (CollectionUtil.isNotEmpty(baseEarningsSummaryVOS)){
//                for (BaseEarningsSummaryVO vo : baseEarningsSummaryVOS){
//                    PageData pd = new PageData();
//                    pd.put("id", vo.getId());
//                    pd.put("UNITNAME", vo.getFillingOrgName());
//                    pd.put("APPLICANTNAME", vo.getCreateUserName());
//                    pd.put("applicantId", vo.getCreateUser());
//                    pd.put("applyOrganizationId", vo.getCreateCompanyId());
//                    pd.put("formType", vo.getFormType());
//                    pd.put("orgName", vo.getFillingOrgName());
//                    pageDataList.add(pd);
//                }
//            }
//
//            return pageDataList;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return pageDataList;
//    }
//
//    /**
//     * QM_EARNING_EXECUTION_REPORT_GZW
//     * @return
//     */
//    @Override
//    public List<Integer> getFormType() {
//        return Arrays.asList(QM_EARNING_REPORT, QM_EARNING_REPORT_GZW);
//    }
//
//    @Override
//    public void goBackToStash(String formId) {
//        handleStatus(Long.valueOf(formId), UNREVIEWED, null);
//    }
//
//    /**
//     * 统一处理状态机事件方法
//     *
//     * @param id          主键
//     * @param updateStatus  更新状态
//     * @return boolean
//     */
//    private Boolean handleStatus(Long id, int updateStatus, String comment) {
//        try {
//            BaseEarningsSummary baseEarningsSummary = getById(id);
//            /**
//             * 设置审批人和审批时间
//             */
//            if (updateStatus == FormStatusConstant.FINISH){
//                baseEarningsSummary.setApprovedUser(TokenUtil.getTokenUserId());
//                Date now = DateUtil.now();
//                baseEarningsSummary.setApprovedTime(now);
//            }
//
//            if (StringUtil.isNotBlank(baseEarningsSummary.getDataSource()) &&StringUtil.isNotBlank(baseEarningsSummary.getDataSourceId())){
//                if (updateStatus == FormStatusConstant.FINISH || updateStatus == FormStatusConstant.REJECT){
//                    ApprovalMessage approvalMessage = new ApprovalMessage();
//                    approvalMessage.setDataSourceId(baseEarningsSummary.getDataSourceId());
//                    approvalMessage.setType(INVESTMENT_EXECUTION);
//                    approvalMessage.setOpinion(comment);
//                    approvalMessage.setIsApprove(updateStatus == FormStatusConstant.FINISH ? 2 : 1);
//                    approvalMessage.setIsSend(1);
//                    approvalMessage.setDataSourceType(KT_TYPE);
//                    if (baseEarningsSummary.getDataSource().equals(YthConstant.DATA_NINGBO)) {
//                        approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
//                        approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
//                        approvalMessage.setFormType(Integer.parseInt(baseEarningsSummary.getFormType()));
//                        approvalMessage.setFilingCode(baseEarningsSummary.getCode());
//                    }
//                    approvalMessageService.save(approvalMessage);
//                }
//            }
//
//            baseEarningsSummary.setStatus(updateStatus);
//            updateById(baseEarningsSummary);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//
//    @Override
//    @Transactional(rollbackFor = RuntimeException.class)
//    public String saveBaseEarningsSummary(String data){
//        YthResult ythResult = new YthResult();
//        //成功的id集合
//        List<String> successIds = new ArrayList<>();
//        //失败的id集合
//        List<String> failIds = new ArrayList<>();
//        //失败的原因
//        List<String> failReasons = new ArrayList<>();
//        //将json字符串转换成list
//        List<BaseEarningsSummary> dataList = JSON.parseArray(data, BaseEarningsSummary.class);
//        if (CollectionUtil.isNotEmpty(dataList)){
//            Map<String, String> orgSourceMap = orgService.getSourceId();
//            Map<String, String> userSourceMap = userService.getSourceId();
//            //根据datasourceIds 查询出所有的数据
//            List<BaseEarningsSummary> list = list(new LambdaQueryWrapper<BaseEarningsSummary>().in(BaseEarningsSummary::getDataSourceId, dataList.stream().map(BaseEarningsSummary::getDataSourceId).toArray()));
//            //如果数据库中有数据，就更新，没有就新增
//            for (BaseEarningsSummary entity:dataList){
//                transfer(entity,orgSourceMap,userSourceMap);
//                //id重复略过
//                if (CollectionUtil.isNotEmpty(list)){
//                    List<String> olIds = list.stream().map(BaseEarningsSummary::getDataSourceId).collect(Collectors.toList());
//                    String dataSourceId = entity.getDataSourceId();
//                    //判断数据库中是否有数据
//                    if (olIds.contains(dataSourceId)){
//                        for (BaseEarningsSummary oldEntity:list){
//                            if (dataSourceId.equals(oldEntity.getDataSourceId())){
//                                //判断status是否为0，如果是0，就更新，不是0，就不更新
//                                if (CheckStatus.checkCode(oldEntity.getStatus())){
//                                    successIds.add(dataSourceId);
//                                    entity.setId(oldEntity.getId());
//                                    entity.setDataSource(YthConstant.DATA_NINGBO);
//                                    entity.setFormType(String.valueOf(FormTypeConstant.QM_EARNING_REPORT));
//                                    submit(entity);
//                                    list.remove(oldEntity);
//                                    break;
//                                }else {
//                                    failIds.add(dataSourceId);
//                                    failReasons.add("dataSourceId:"+dataSourceId+"数据已提交且已经在流程中，无法更新");
//                                    break;
//                                }
//                            }
//                        }
//                    }else {
//                        //如果数据库中没有数据，就新增
//                        entity.setDataSource(YthConstant.DATA_NINGBO);
//                        submit(entity);
//                        successIds.add(entity.getDataSourceId());
//                    }
//                }else {
//                    //如果数据库中没有数据，就新增
//                    entity.setDataSource(YthConstant.DATA_NINGBO);
//                    submit(entity);
//                    successIds.add(entity.getDataSourceId());
//                }
//            }
//        } else {
//            failReasons.add("数据为空");
//        }
//        ythResult.setSuccessIds(successIds);
//        ythResult.setFailIds(failIds);
//        ythResult.setFailReason(StringUtils.join(failReasons, ";"));
//        //ythResult转换成json字符串
//        return JSON.toJSONString(ythResult);
//    }
//
//    private void transfer(BaseEarningsSummary entity, Map<String, String> orgSourceMap, Map<String, String> userSourceMap){
//        Optional.ofNullable(entity.getFillingOrgId()).ifPresent(m ->
//                {
//                    String orgId = orgSourceMap.get(m);
//                    if (StringUtil.isNotBlank(orgId)){
//                        entity.setCreateCompanyId(orgId);
//                        entity.setFillingOrgId(orgId);
//                    }
//                }
//        );
//        Optional.ofNullable(entity.getCreateUser()).ifPresent(m ->
//                {
//                    String userId = userSourceMap.get(m);
//                    if (StringUtil.isNotBlank(userId)){
//                        entity.setCreateUser(userId);
//                    }
//                }
//        );
//    }
//}
